﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.ComponentModel;

namespace Kokomo
{
	public class PropertyValueConverter : IValueConverter
	{
		public PropertyValueConverter(
			TypeConverter converter
			)
		{
			if (converter == null) throw new ArgumentNullException("converter");

			this.Converter = converter;
		}

		public TypeConverter Converter { get; private set; }

		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
			{
				// This happens with DataGridCheckBoxColumn
				targetType = targetType.GetGenericArguments()[0];
			}

			if (targetType.IsInstanceOfType(value)) return value;

			object convertedValue = this.Converter.ConvertTo(value, targetType);
			return convertedValue;
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			object convertedValue = this.Converter.ConvertFrom(value);
			return convertedValue;
		}
	}
}
